//
//  CZSplitViewController.m
//  QQ空间
//
//  Created by zhangping on 16/1/15.
//  Copyright © 2016年 zhangping. All rights reserved.
//

#import "CZSplitViewController.h"
#import "CZMenuViewController.h"
#import "CZDetailViewController.h"

@interface CZSplitViewController ()

@end

@implementation CZSplitViewController

- (instancetype)init {
    if (self = [super init]) {
        // 添加master控制器
        [self addChildViewController:[[CZMenuViewController alloc] init]];
        
        // 添加detail控制器
        CZDetailViewController *detailVC = [[CZDetailViewController alloc] init];
        [self addChildViewController:detailVC];
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self prepareSplitViewController];
}

#pragma mark - 设置 UISplitViewController
/// 设置master 控制器横竖屏显示以及宽度
- (void)prepareSplitViewController {
    // 1. 一直显示master控制器
    self.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
    
    // 2. 根据屏幕方向设置master控制器的宽度
    [self setPrimaryColumnWidthWithOrientation:[UIApplication sharedApplication].statusBarOrientation];
    
    self.view.backgroundColor = CZCommonBGColor;
}

/**
 *  根据屏幕方向设置master的宽度
 *  @param orientation 屏幕方向
 */
- (void)setPrimaryColumnWidthWithOrientation:(UIInterfaceOrientation)orientation {
    BOOL isLandscape = UIInterfaceOrientationIsLandscape(orientation);
    
    // 设置master控制器的宽度
    if (isLandscape) {
        self.maximumPrimaryColumnWidth = 280;
    } else {
        self.maximumPrimaryColumnWidth = 60;
    }
    
    // 获取menuVC更新子控件
    [[self menuViewController] updateSubViews:isLandscape];
}

#pragma mark - sizeClass
/// 当控制器的sizeClass发生改变的时候调用
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    
    // 判断是否显示iPhone界面
    BOOL isShow = self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact;
    
    // 调用 CZMenuViewController 来显示或隐藏 iPhone 界面
    [[self menuViewController] showContainerView:isShow];
}

/// 获取 CZMenuViewController
- (CZMenuViewController *)menuViewController {
    CZMenuViewController *menuVC = self.viewControllers[0];
    
    // 判断 menuVC 是否真的是 CZMenuViewController 类型
    if (![menuVC isKindOfClass:[CZMenuViewController class]]) {
        return nil;
    }
    
    return menuVC;
}

@end
